import datetime, re
from PyQt5.QtCore import pyqtSignal
from resources.separate_data import Separate_Form
from new_func.tools import Tool
from PyQt5.QtWidgets import QFrame


class SeparateWidget(QFrame, Separate_Form):
    error = pyqtSignal()
    warn = pyqtSignal()

    def __init__(self, text, parent=None):
        super(SeparateWidget, self).__init__(parent=parent)
        # self.unpack_ui = Separate_Form()
        # self.unpack_ui.setupUi(self)
        self.setupUi(self)
        self.setObjectName(text.replace(' ', '-'))

        self.tool = Tool()
        self.signals()

    def signals(self):
        """按钮触发"""
        self.separate_get_file.clicked.connect(lambda: self.tool.handle_path(self.separate_line))
        self.separate_line.textChanged.connect(self.suffix_info)

    def suffix_info(self):
        """检测后缀"""
        self.tool.get_suffix(self.separate_line)
        if self.tool.suffix != '.log':
            self.tool.show_error(self, "❗️文件错误", "文件后缀错误")

    @staticmethod
    def data_times(value, stime, etime):
        if len(value) >= 12:
            start_time = datetime.datetime.strptime(stime, '%H:%M:%S.%f')
            end_time = datetime.datetime.strptime(etime, '%H:%M:%S.%f')
        else:
            start_time = datetime.datetime.strptime(stime, '%H:%M:%S')
            end_time = datetime.datetime.strptime(etime, '%H:%M:%S')
        over_time = end_time - start_time
        return str(over_time)

    def read_data(self, path_name, args1='batterry', args2='motor'):
        if path_name:
            with open(path_name, 'r', encoding='utf-8') as r:
                datas = r.read()
                matches = re.findall(r'<{}>(.*?)<{}>'.format(args1, args2), datas, re.DOTALL)
                return matches
        else:
            self.warn.emit()

    def get_info_batterry_time(self):
        """info充放电时长"""
        data_time = None
        sta = self.tool.get_text(self.appoint_time)
        path_name = self.tool.get_text(self.separate_line)
        if path_name:
            matches = self.read_data(path_name)
            status = self.read_data(path_name, "charge", "warn")
            # 时长
            time_list = [re.search(r'\[(.*)\].*cap\s*:\s*(\d+)\s*%', cap).group(1) for cap in matches]
            # 状态
            status_list = [re.search(r'\[(.*)\].*status\s*:\s*(\w*)', sta).group(2) for sta in status]
            try:
                if sta == "放电":  # 放电
                    data_time = "放电用时 {}".format(
                        self.data_times(stime=time_list[0], etime=time_list[-1], value=time_list[-1]))
                if sta == "充电":  # 充电
                    full_index = status_list.index('full', 0)
                    if full_index:  # 找到充电中存在的第一个full
                        data_time = "充电用时 {}".format(
                            self.data_times(stime=time_list[0], etime=time_list[full_index], value=time_list[0]))
            except:
                data_time = '日志数据有误，没有对应数据，请使用筛选指定时长功能'
        else:
            self.error.emit()
        self.write_text(data_time)

    def specify_calculation(self):
        """计算指定时长"""
        path_name = self.tool.get_text(self.separate_line)
        start = self.bat_1.text()
        end = self.bat_2.text()
        matches = self.read_data(path_name)
        # 时长
        cap_list = [re.search(r'\[(.*)\].*cap\s*:\s*(\d+)\s*%', cap).group(2) for cap in matches]
        time_list = [re.search(r'\[(.*)\].*cap\s*:\s*(\d+)\s*%', cap).group(1) for cap in matches]
        if start and end:
            if start and end in cap_list:
                start_index = cap_list.index(start, 0)
                end_index = cap_list.index(end, 0)
                if start_index and end_index:
                    data_time = "用时 {}".format(
                        self.data_times(stime=time_list[start_index], etime=time_list[end_index], value=time_list[-1]))
                    # print(data_time)
                    self.write_text(data_time)
            else:
                self.error.emit()
        else:
            self.warn.emit()

    def get_info_jump(self):
        """info跳电"""
        sta = self.tool.get_text(self.btn_info_jump)
        path_name = self.tool.get_text(self.separate_line)
        print(sta, path_name)

        matches = self.read_data(path_name)
        try:
            cap_list, time_list, jump_list = [], [], []
            for values in matches:
                pattern = re.compile(r'\[(.*)\].*cap\s*:\s*(\d+)\s*%')
                for line in values.split('\n'):
                    match = pattern.match(line)
                    if match:
                        cap_value, time_ = match.group(2), match.group(1).strip()
                        cap_list.append(cap_value)
                        time_list.append(time_)
            if sta == "放电":  # 放电
                for num, (value, time) in enumerate(zip(cap_list[:-1], time_list[:-1])):
                    # 第一个减去第二个...放电
                    jump_bat = int(cap_list[num]) - int(cap_list[num + 1])
                    if jump_bat == 0:
                        continue
                    if jump_bat < 0:
                        jump_list.append(f"up：{time} {jump_bat}")
                    if jump_bat > 1:
                        jump_list.append(f"down：{time} {jump_bat}")
            if sta == "充电":  # 充电
                for num, (value, time) in enumerate(zip(cap_list[:-1], time_list[:-1])):
                    # 第二个减去第一个...充电
                    jump_bat = int(cap_list[num + 1]) - int(cap_list[num])
                    if jump_bat == 0:
                        continue
                    if jump_bat < 0:
                        jump_list.append(f"down：{time} {jump_bat}")
                    if jump_bat > 1:
                        jump_list.append(f"up：{time} {jump_bat}")
        except:
            jump_list = ["日志数据有丢失"]
        if len(jump_list) == 0:
            jump_list = ["日志数据无跳电，或请检查充放电选择是否选错"]
        self.write_text(jump_list)

    def get_bat_jump(self):
        """bat跳电"""
        list_ = []
        sta = self.tool.get_text(self.btn_bat_jump)
        path_name = self.tool.get_text(self.separate_line)
        with open(path_name, 'r', encoding='utf-8') as r:
            datas = r.read()
            values = re.findall(r'(\[.*])\s*cap\s*:\s*.*, (\w*)', datas)
        try:
            if sta == '放电':
                """放电"""
                for i in range(len(values) - 1):
                    if int(values[i][1]) - int(values[i + 1][1]) > 1:
                        data = "jump " + "前 " + values[i][0] + values[i][1] + " 后 " + values[i + 1][0] + values[i + 1][
                            1]
                        list_.append(data)
                    if int(values[i][1]) - int(values[i + 1][1]) < 0:
                        data = "jump " + "前 " + values[i][0] + values[i][1] + " 后 " + values[i + 1][0] + values[i + 1][
                            1]
                        list_.append(data)
            if sta == '充电':
                """充电"""
                for i in range(len(values) - 1):
                    if int(values[i + 1][1]) - int(values[i][1]) > 1:
                        data = "jump 前 " + values[i][0] + values[i][1] + " 后 " + values[i + 1][0] + values[i + 1][1]
                        list_.append(data)
                    if int(values[i + 1][1]) - int(values[i][1]) < 0:
                        data = "jump 前 " + values[i + 1][0] + values[i][1] + " 后 " + values[i + 1][0] + values[i + 1][1]
                        list_.append(data)
        except:
            list_ = ["数据文件有缺失"]
        if len(list_) == 0:
            list_ = ["这里是“bat”选项数据，日志数据无跳电，或请检查充放电选择是否选错"]
        self.write_text(list_)

    def write_text(self, value):
        """写入文本"""
        if self.independent_text.toPlainText():
            self.independent_text.clear()
        if isinstance(value, list):
            for text in value:
                self.independent_text.insertPlainText(text + '\n')
        if isinstance(value, str):
            self.independent_text.insertPlainText(value)
